# -*- coding:utf-8 -*-
# @FileName : app\api\v1\chat\services.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""Chat API 服务层文件

此模块实现了 Chat API 的业务逻辑。
"""
from app.config import logger
from typing import Optional, Tuple, Dict, Any
from app.models.conversation import Conversation, Message
from app.models.task_execution import TaskExecution
from app.extensions import db


def save_user_message(conversation_id: str, message_content: str) -> Tuple[bool, str]:
    """
    保存用户消息到数据库
    
    Args:
        conversation_id (str): 对话ID
        message_content (str): 用户消息内容
        
    Returns:
        tuple: (success: bool, error_message: str)
    """
    try:
        # 将conversation_id转换为整数类型
        conv_id = int(conversation_id)
        
        # 验证对话是否存在
        conversation = Conversation.query.get(conv_id)
        if not conversation:
            return False, "对话不存在"
        
        # 创建用户消息记录
        user_message = Message(
            conversation_id=conv_id,
            role="user",
            content=message_content
        )
        
        # 保存到数据库
        db.session.add(user_message)
        db.session.commit()
        
        logger.info(f"成功保存用户消息到对话 {conv_id}")
        return True, ""
    except ValueError:
        logger.error(f"无效的对话ID格式: {conversation_id}")
        return False, "无效的对话ID格式"
    except Exception as e:
        db.session.rollback()
        logger.error(f"保存用户消息失败: {str(e)}")
        return False, str(e)


def save_ai_response(conversation_id: str, response_content: str, execution_id: Optional[int] = None) -> Tuple[bool, str]:
    """
    保存AI响应消息到数据库
    
    Args:
        conversation_id (str): 对话ID
        response_content (str): AI响应内容
        execution_id (Optional[int]): 任务执行ID（如果有）
        
    Returns:
        tuple: (success: bool, error_message: str)
    """
    try:
        # 将conversation_id转换为整数类型
        conv_id = int(conversation_id)
        
        # 验证对话是否存在
        conversation = Conversation.query.get(conv_id)
        if not conversation:
            return False, "对话不存在"
        
        # 准备元数据
        meta_data = {}
        if execution_id:
            meta_data["execution_id"] = execution_id
            
        # 创建AI消息记录
        ai_message = Message(
            conversation_id=conv_id,
            role="assistant",
            content=response_content,
            meta_data=meta_data if meta_data else None
        )
        
        # 保存到数据库
        db.session.add(ai_message)
        db.session.commit()
        
        logger.info(f"成功保存AI响应到对话 {conv_id}")
        return True, ""
    except ValueError:
        logger.error(f"无效的对话ID格式: {conversation_id}")
        return False, "无效的对话ID格式"
    except Exception as e:
        db.session.rollback()
        logger.error(f"保存AI响应失败: {str(e)}")
        return False, str(e)


def get_task_execution_detail(execution_id: int) -> Tuple[bool, str, Optional[Dict[str, Any]]]:
    """
    获取任务执行详情
    
    Args:
        execution_id (int): 任务执行ID
        
    Returns:
        tuple: (success: bool, error_message: str, data: Optional[Dict])
    """
    try:
        # 查询任务执行记录
        execution = TaskExecution.query.get(execution_id)
        if not execution:
            return False, "任务执行记录不存在", None
        
        # 查询关联的步骤记录
        steps = execution.steps
        
        # 构造返回数据
        execution_data = {
            "execution": {
                "id": execution.id,
                "conversation_id": execution.conversation_id,
                "status": execution.status.value if execution.status else None,
                "summary": execution.summary,
                "assertion_result": execution.assertion_result,
                "assertion_reason": execution.assertion_reason,
                "created_at": execution.created_at.isoformat() if execution.created_at else None,
                "updated_at": execution.updated_at.isoformat() if execution.updated_at else None
            },
            "steps": [
                {
                    "id": step.id,
                    "execution_id": step.execution_id,
                    "step_number": step.step_number,
                    "action_type": step.action_type.value if step.action_type else None,
                    "description": step.description,
                    "screenshot_path": step.screenshot_path,
                    "status": step.status.value if step.status else None,
                    "created_at": step.created_at.isoformat() if step.created_at else None,
                    "updated_at": step.updated_at.isoformat() if step.updated_at else None
                }
                for step in steps
            ]
        }
        
        return True, "", execution_data
    except Exception as e:
        logger.error(f"获取任务执行详情失败: {str(e)}")
        return False, str(e), None


def get_conversation_history(conversation_id: str) -> Tuple[bool, str, Optional[Dict[str, Any]]]:
    """
    获取对话历史记录
    
    Args:
        conversation_id (str): 对话ID
        
    Returns:
        tuple: (success: bool, error_message: str, data: Optional[Dict])
    """
    try:
        logger.info(f"开始获取对话历史，对话ID: {conversation_id}")
        
        # 将conversation_id转换为整数类型
        conv_id = int(conversation_id)
        logger.info(f"转换后的对话ID: {conv_id}")
        
        # 验证对话是否存在
        conversation = Conversation.query.get(conv_id)
        if not conversation:
            logger.warning(f"对话不存在，对话ID: {conv_id}")
            return False, "对话不存在", None
        
        # 查询关联的消息记录，按创建时间排序
        messages = Message.query.filter_by(conversation_id=conv_id).order_by(Message.created_at.asc()).all()
        logger.info(f"查询到 {len(messages)} 条消息记录")
        
        # 构造返回数据
        messages_data = []
        for msg in messages:
            try:
                msg_dict = {
                    "id": msg.id,
                    "conversation_id": msg.conversation_id,
                    "role": msg.role,
                    "content": msg.content,
                    "image_path": msg.image_path,
                    "meta_data": msg.meta_data,
                    "created_at": msg.created_at.isoformat() if msg.created_at else None
                }
                messages_data.append(msg_dict)
            except Exception as msg_e:
                logger.error(f"处理消息记录失败，消息ID: {msg.id if hasattr(msg, 'id') else '未知'}，错误: {str(msg_e)}")
                # 跳过有问题的消息，继续处理其他消息
                continue
        
        result = {"messages": messages_data}
        logger.info(f"成功获取对话历史，返回 {len(messages_data)} 条消息")
        return True, "", result
    except ValueError:
        logger.error(f"无效的对话ID格式: {conversation_id}")
        return False, "无效的对话ID格式", None
    except Exception as e:
        logger.error(f"获取对话历史记录失败: {str(e)}")
        import traceback
        logger.error(f"异常堆栈: {traceback.format_exc()}")
        return False, str(e), None